package de.preisrobot.persistence.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import de.preisrobot.entity.Tb_Category;

@Repository
public class CategoryDaoImpl implements CategoryDao {

	private static Logger log = Logger.getLogger(CategoryDaoImpl.class);

	@PersistenceContext
	EntityManager em;

	@Override
	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public long save(Tb_Category c) {
		em.persist(c);
		return c.getId();
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void saveNode(Object c) {
		em.persist(c);
	}

	@Override
	public Tb_Category find(long id) {
		return em.find(Tb_Category.class, id);
	}

	@Override
	public Tb_Category findByName(String name) {
		Query createQuery = em
				.createQuery("select c from Category c where c.name like ?1");
		createQuery.setParameter(1, name);
		List<Tb_Category> resultList = createQuery.getResultList();
		if (resultList.isEmpty())
			return null;

		return (Tb_Category) resultList.get(0);
	}

	@Override
	public List<Tb_Category> findAllByName(String name) {
		Query createQuery = em
				.createQuery("select c from Category c where c.name like ?1");
		createQuery.setParameter(1, name);
		List<Tb_Category> resultList = createQuery.getResultList();

		return resultList;
	}

}
